home *** CD-ROM | disk | FTP | other *** search
- /* Figure 2 - Slightly Enhanced Binary Tree Program - */
-
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
-
- /* Tree Node Definition with String Key */
-
- typedef struct node {
- struct node *left;
- struct node *right;
- char key[BUFSIZ];
- }node;
-
-
- /* Non-Recursive Tree Insertion Function */
-
- void tree_insert(node **root, node *new_node)
- {
- node *this_node = *root;
- int dif;
-
- while(this_node) {
- if(! (dif = strcmp(new_node->key, this_node->key)))
- goto key_copy;
- else if(dif < 0) {
- if(this_node->left)
- this_node = this_node->left;
- else {
- this_node->left = (node *)calloc(1, sizeof(node));
- this_node = this_node->left;
- goto key_copy;
- }
- }
- else {
- if(this_node->right)
- this_node = this_node->right;
- else {
- this_node->right = (node *)calloc(1, sizeof(node));
- this_node = this_node->right;
- goto key_copy;
- }
- }
- }
-
- /*
- * only arrives here when instatiating root
- */
- this_node = (node *)calloc(1, sizeof(node));
- *root = this_node;
-
- key_copy:
- strncpy(this_node->key, new_node->key, BUFSIZ);
- this_node->key[BUFSIZ] = '\0';
- }
-
- /* Recursive In-Order Traversal Function Prints Key String */
-
- void tree_trace(node *root)
- {
- if(! root)
- return;
- tree_trace(root->left);
- printf("%s\n", root->key);
- tree_trace(root->right);
- }
-
- /* String Key Tree Test Driver */
-
- void main(void)
- {
- node *tree_root = NULL;
- node this_node = { NULL, NULL, "" };
- char *str[5] = { "some", "duplicate", "and", "duplicate", "keys" };
- int i;
-
- for(i = 0;i < 5;i++) {
- strcpy(this_node.key, str[i]);
- tree_insert(&tree_root, &this_node);
- }
- tree_trace(tree_root);
- exit(0);
- }
-